/*
 * @Description: 分页查询hook
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-03-30
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2025-06-12
 */

import { reactive, readonly, Ref, ref } from 'vue'

import { DEFAULT_PAGE_SIZE } from '../enums/commonEnum'

interface IConfig {
  success?: () => void
}

/**
 * 分页查询
 * @param query 请求入参
 * @param fn 请求方法
 * @returns
 */
export const useQueryPagination = <T extends object, S>(query: T, fn: (x: T) => Promise<IPaginationResponse<S>>, config?: IConfig) => {
  // 加载中
  const loading = ref(false)
  // 首次加载完成
  const initialLoaded = ref(false)
  // 数据列表
  const dataList: Ref<S> = ref([]) as Ref<S>
  // 分页
  const pagination: IBasePage = reactive({
    current: 1,
    page: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    total: 0,
  })

  /**
   * 获取列表
   */
  const queryList = async (_pagination?: IBasePage, param?: any) => {
    loading.value = true
    try {
      const current = _pagination?.page ?? pagination.page
      const page = current,
        pageIndex = current
      const pageSize = _pagination?.pageSize ?? pagination.pageSize
      const { responseData } = await fn({ page, pageIndex, pageSize, ...query, ...param })
      dataList.value = responseData.list
      pagination.total = parseInt(responseData.total)
      pagination.current = current
      pagination.page = current
      pagination.pageIndex = current
      pagination.pageSize = pageSize
      if (!initialLoaded.value) initialLoaded.value = true
      config?.success?.()
    } catch (error) {
    } finally {
      loading.value = false
    }
  }

  /**
   * 监听分页改变回调
   */
  const onPaginationChange = (pageParam) => {
    const { current, pageSize } = pageParam
    if (pagination.pageSize === pageSize) {
      pagination.current = current
      pagination.page = current
      pagination.pageIndex = current
    } else {
      pagination.current = 1
      pagination.page = 1
      pagination.pageIndex = 1
      pagination.pageSize = pageSize
    }
    dataList.value = [] as S
    queryList()
  }

  return {
    initialLoaded: readonly(initialLoaded),
    loading: readonly(loading),
    queryList,
    dataList: dataList,
    pagination,
    onPaginationChange,
  }
}
